package com.hubiao.pay.merchant.service.impl;

import com.hubiao.pay.common.domain.BusinessException;
import com.hubiao.pay.common.domain.CommonErrorCode;
import com.hubiao.pay.common.util.QiniuUtils;
import com.hubiao.pay.merchant.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * Description
 *
 * @author hubiao
 * @since 2020-11-09 22:15
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {


    @Value("${oss.qiniu.url}")
    private String qiniu_url;
    @Value("${oss.qiniu.accessKey}")
    private String accessKey;
    @Value("${oss.qiniu.secretKey}")
    private String secretKey;
    @Value("${oss.qiniu.bucket}")
    private String bucket;

    /**
     * 上传附件
     *
     * @param multipartFile 附件
     * @return 文件名
     * @throws BusinessException
     */
    @Override
    public String upload(MultipartFile multipartFile) throws BusinessException {
        String fileName = "";
        try {
            //1.构造文件名称
            //1.1 获取原文件名
            String originalFilename = multipartFile.getOriginalFilename();
            //1.2 拼接新文件名
            fileName = UUID.randomUUID() + originalFilename.substring( originalFilename.lastIndexOf( "." ) );
            log.info( "附件名称：源文件名{},新文件名{}", originalFilename, fileName );
            //2.调用common下面得工具类QiniuUtils
            QiniuUtils.upload2qiniu( accessKey, secretKey, bucket, multipartFile.getBytes(), fileName );
        } catch (Exception e) {
            log.error( "附件上传失败,class:{}，method:{},errorMsg:{}", "FileServiceImpl", "upload", e.getMessage() );
            e.printStackTrace();
            throw new BusinessException( CommonErrorCode.E_100116 );
        }
        return qiniu_url + fileName;
    }
}
